package vip.bblog.dynamic.datasource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @author <a href="1396513066@qq.com">Yu Yong</a>
 * @version 1.0
 * @date 2019年04月26日 17:04
 * @desc DynamicDataSourceAutoConfiguration 自动配置
 */
@Configuration
@EnableConfigurationProperties(DynamicDataSourceProperty.class)
public class DynamicDataSourceAutoConfiguration {

    @Autowired
    private DynamicDataSourceProperty dataSourceProperty;

    @Bean
    @ConditionalOnMissingBean
    public DynamicDataSourceRegister dynamicDataSourceRegister() {
        DynamicDataSourceRegister dynamicDataSourceRegister = new DynamicDataSourceRegister();
        dynamicDataSourceRegister.setDataSourceProperty(dataSourceProperty);
        return dynamicDataSourceRegister;
    }

    @Bean
    public DataSource dataSource(DynamicDataSourceRegister dynamicDataSourceRegister) {
        DynamicDataSourceRouting dataSource = new DynamicDataSourceRouting();
        dataSource.setTargetDataSources(dynamicDataSourceRegister.getTargetDataSources());
        dataSource.setDefaultTargetDataSource(dynamicDataSourceRegister.getDefaultTargetDataSource());
        return dataSource;
    }
}
